package org.crmsystem.controller.shiro;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.crmsystem.model.Permission;
import org.crmsystem.model.Role;
import org.crmsystem.model.User;
import org.crmsystem.service.IPermissionService;
import org.crmsystem.service.IRoleService;
import org.crmsystem.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
/**
 * 自定义的用户拦截器
 * @author 孙艳平
 *
 */
public class UserRealm extends AuthorizingRealm {

	private Logger logger=LogManager.getLogger(UserRealm.class);
	@Autowired
	private IUserService iUserService;
	@Autowired
	private IRoleService iRoleService;
	@Autowired
	private IPermissionService iPermissionService;
	/**
	 * 授权
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		User user=(User)principals.getPrimaryPrincipal();
		List<Permission> permissionList=null;
		//根据用户ID查询角色（role），放入到Authorization里。
		User user1= this.iUserService.getUserById(user.getId());
		int roleId=user1.getRoleId();
		permissionList=this.iPermissionService.getPermissionByRoleId(roleId);
		SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();
		for(Permission p:permissionList){
			info.addStringPermission(p.getName());
		}
		return info;
	}

	/**
	 * 认证
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException{
		String username=token.getPrincipal().toString();
		User user1=iUserService.getUserByName(username);
		if(null == user1){
			throw new AccountException("帐号或密码不正确！");
		/**
		 * 如果用户的status为禁用。那么就抛出<code>DisabledAccountException</code>
		**/
		}else if("禁用".equals(user1.getUseState())){
			throw new DisabledAccountException("帐号已经禁止登录！");
		}else{
			return new SimpleAuthenticationInfo(user1,user1.getPassword(), getName());
		}
	}
	/**
	 * 清空缓存
	 */
	public void clearCached() {
		PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
		super.clearCache(principals);
	}	
}
